import Taro, { Component } from "@tarojs/taro";
import {
  View,
  Image,
  ScrollView,
  Text,
  Swiper,
  SwiperItem
} from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { getAppconfig } from "../../actions/appconfig";
import { getBanner, getTaskList, getSearchTags } from "../../actions/task";
import { removeCache } from "../../utils/cache";
import { APP_CACHE_KEY } from "../../service/config";
import LoginModal from "../../components/modal/loginModal";
import Item from "../../components/task/item";
import "./index.less";

@connect(
  ({ appconfig, task, account }) => ({
    ...appconfig,
    ...task,
    ...account
  }),
  dispatch => ({
    async getAppconfig() {
      dispatch(await getAppconfig());
    },
    async getTaskList(params) {
      dispatch(await getTaskList(params));
    },
    async getBanner() {
      dispatch(await getBanner());
    },
    async getSearchTags() {
      dispatch(await getSearchTags());
    }
  })
)
class Index extends Component {
  config = {
    navigationBarTitleText: "首页"
  };

  state = {
    page: 1,
    currentType: 3,
    isOpened: false,
    tags: [
      {
        title: "分享赚钱",
        active: true,
        activeClass:'tag-active-kb',
        img:'kb',
        type: 3
      },
      {
        title: "邀约赚钱",
        active: false,
        activeClass:'tag-active-dd',
        img:'dd',
        type: 1
      },
      {
        title: "成交赚钱",
        active: false,
        activeClass:'tag-active-cd',
        img:'cd',
        type: 2
      },
      {
        title: "销售素材",
        active: false,
        activeClass:'tag-active-xs',
        img:'xs',
        type: 4
      }
    ]
  };

  async componentWillMount() {
    removeCache(APP_CACHE_KEY);
    this.props.getAppconfig && (await this.props.getAppconfig());
    this.props.getBanner && (await this.props.getBanner());
    this.props.getTaskList &&
      (await this.props.getTaskList({ page: 1, type: 3 }));
    this.props.getSearchTags && (await this.props.getSearchTags());
  }

  changeActive(index) {
    let { tags } = this.state;
    tags.forEach((item, i) => {
      if (i === index) {
        item.active = true;
      } else {
        item.active = false;
      }
    });
    this.setState(
      {
        tags,
        currentType: tags[index].type
      },
      async () => {
        await this.props.getTaskList({ page: 1, type: this.state.currentType });
      }
    );
  }

  handleOnScrollToUpper() {
    const { currentType } = this.state;
    this.setState(
      {
        page: 1
      },
      async () => {
        await this.props.getTaskList({ page: 1, type: currentType });
      }
    );
  }

  handleOnScrollToLower() {
    const { list } = this.props;
    if (list.length > 0 && list.length % 10 === 0) {
      const { currentType, page } = this.state;
      this.setState(
        {
          page: page + 1
        },
        async () => {
          await this.props.getTaskList({
            page: this.state.page,
            type: currentType
          });
        }
      );
    }
  }

  render() {
    const { banners, list, staticUri,nomore,id } = this.props;
    // const clientHeight = document.getElementById("app").clientHeight - 305;
    return (
      <View className="home-index">
        {/* <View className="search">
          <View
            className="search-con"
            onClick={() => {
              Taro.navigateTo({
                url: "/pages/index/search"
              });
            }}
          >
            <View style="padding-left:15px;padding-bottom:3px;">
              <AtIcon value="search" size="20" color="#409EFF" />
            </View>
            <View style="padding-left:15px;padding-bottom:5px;">
              <Text className="search-text">搜索</Text>
            </View>
          </View>
        </View> */}

        <View className="home-body">
          <Swiper
            className="swiper-home-con"
            indicatorColor="#999"
            indicatorActiveColor="#333"
            circular
            indicatorDots
            autoplay
          >
            {banners.length > 0 &&
              banners.map(item => (
                <SwiperItem key={item.taskid}>
                  <Image
                    style="width:100%;height:150px;"
                    onClick={() => {
                      if (!this.props.token) {
                        this.setState({
                          isOpened: true
                        });
                      } else {

                        if (item.type === 4) {
                          removeCache(CONTENT_OF_TASK)
                            Taro.redirectTo({
                              url:'/pages/index/sharecontent?id='+item.id+'&puser='+ id
                            })
                        } else {
                          Taro.redirectTo({
                            url:
                              "/pages/index/task?id=" +
                              item.taskid +
                              "&type=" +
                              item.type
                          });
                        }
                      }
                    }}
                    src={staticUri + item.url}
                  />
                </SwiperItem>
              ))}
          </Swiper>
          <View className={{ tags: true }}>
            {this.state.tags.map((item, index) => (
              <View
                className="tags-info"
                onClick={this.changeActive.bind(this, index)}
              >
                <Image className="tag-img" src={require('../../assets/img/'+item.img+'.png')} />
                <View
                  className={item.active ? `tag-name ${item.activeClass}` : 'tag-name'}
                >
                  {item.title}
                </View>
              </View>
            ))}
          </View>
          <ScrollView
            className="container"
            scrollY
            style={{ height: '100%' }}
            scrollWithAnimation
            scrollTop="0"
            lowerThreshold="10"
            onScrollToUpper={this.handleOnScrollToUpper.bind(this)}
            onScrollToLower={this.handleOnScrollToLower.bind(this)}
          >
            <View className="product-list">
              {list.length > 0 ? (
                [
                  list.map((item, index) => {
                    return (
                      <Item
                        parent={this}
                        item={item}
                        index={index}
                        staticUri={staticUri}
                      />
                    );
                  }),
                  (list.length % 10 > 0 || nomore) && (
                    <View style="display:flex;flex-direction:row;justify-content:center">
                      <Text style="font-size:12px;color:#cccccc;">
                        - 没有更多了 -
                      </Text>
                    </View>
                  )
                ]
              ) : (
                <View className="have-no-data">- 暂无数据 -</View>
              )}
            </View>
          </ScrollView>
        </View>
        <LoginModal
          parent={this}
          isOpened={this.state.isOpened}
          info="未登录无法查看任务详情"
        />
      </View>
    );
  }
}

export default Index;
